﻿using System;
using System.Web.Routing;
using System.Web.Mvc;

using Fuse8.DomainFramework.Common.Locator;
using Microsoft.Practices.ServiceLocation;

namespace Fuse8.ContentManagementFramework.Web.ApplicationRuntime
{
    public class CmsControllerFactory : DefaultControllerFactory
    {            
        public override IController CreateController(RequestContext requestContext, string controllerName)
        {
            if (DependencyServiceLocator.Current.IsRegistered<IController>(controllerName))
            {
                return DependencyServiceLocator.Current.GetInstance<IController>(controllerName);
            }
            else
            {
                return base.CreateController(requestContext, controllerName);
            }
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            controllerType = controllerType ??
                (requestContext.HttpContext.IsDebuggingEnabled ?
                    typeof(DynamicDevController) :
                    typeof(PageNotFoundController));
            
            return DependencyServiceLocator.Current.GetInstance(controllerType) as IController;
        }
    }
}
